//
//  AppDelegate.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/16.
//

#import "AppDelegate.h"

#import "AppDelegate+RCConfig.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "HNSH_UploadAppAlert.h"

//#import <XHAdSDK/XHAdSDK.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>
//#import "HNSH_SplashToors.h"

#import "HNSH_LoginHomeViewController.h"

#import "HNSH_AlipayToors.h"       //支付宝工具

@import CoreTelephony;
#import "AFNetworking.h"
#import "AFNetworkActivityIndicatorManager.h"

@interface AppDelegate ()

/* 初始化广告 */
@property (nonatomic, assign) BOOL isHaveAdInfo;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor appWhiteLabelColor];

    //初始化融云 
    [self initRongIM];
    
    //初始化地图
    [self configMap];
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:KUserShowHiddenContentID];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if ([ST_UserManager alreadyLogin]) {
        //隐藏判断
        KUserShowHiddenPhoneID
        if (![ST_UserManager shareInstance].rcUser.token) {
            //请求融云信息
            [[ST_UserManager shareInstance] loadRcUserInfoComplate:^{
                [HNSH_RYTools connectWithToken:[ST_UserManager shareInstance].rcUser.token];
            }];
        } else {
            [HNSH_RYTools connectWithToken:[ST_UserManager shareInstance].rcUser.token];
        }
        self.window.rootViewController = [ST_TabbarViewController new];
    } else {
        HNSH_LoginHomeViewController *vc = [[HNSH_LoginHomeViewController alloc]init];
        ST_BaseNavigationController *nav = [[ST_BaseNavigationController alloc]initWithRootViewController:vc];
        self.window.rootViewController = nav;
    }
    
    //更新
//    [self requestAppStoreConfig];
    
    self.isHaveAdInfo = NO;
    //网络状态监听
//    [self networkStatus:application didFinishLaunchingWithOptions:launchOptions];
    //1.获取网络权限 根绝权限进行人机交互
    if (__IPHONE_10_0) {
        [self networkStatus:application didFinishLaunchingWithOptions:launchOptions];
        
    }else {
        //2.2已经开启网络权限 监听网络状态
        [self addReachabilityManager:application didFinishLaunchingWithOptions:launchOptions];
        
    }
    
    [self loadAPPServerConfig];
    
    //改变状态栏时间颜色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
    [self.window makeKeyAndVisible];
    return YES;
}

/*CTCellularData在iOS9之前是私有类，权限设置是iOS10开始的，所以App Store审核没有问题获取网络权限状态*/
- (void)networkStatus:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //2.根据权限执行相应的交互
    CTCellularData *cellularData = [[CTCellularData alloc] init];
    /*此函数会在网络权限改变时再次调用*/
    cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state) {
        switch (state) {
            case kCTCellularDataRestricted:NSLog(@"Restricted");
                //2.1权限关闭的情况下 再次请求网络数据会弹出设置网络提示
//                [self getAppInfo];
                break;
            case kCTCellularDataNotRestricted:NSLog(@"NotRestricted");
                //2.2已经开启网络权限 监听网络状态
                [self addReachabilityManager:application didFinishLaunchingWithOptions:launchOptions];
//                [self getInfo_application:application didFinishLaunchingWithOptions:launchOptions];
                break;
            case kCTCellularDataRestrictedStateUnknown:NSLog(@"Unknown");
                //2.3未知情况 （还没有遇到推测是有网络但是连接不正常的情况下）
//            [self getAppInfo];
                break;
            default:
                break;
        }
    };
}/**实时检查当前网络状态*/
- (void)addReachabilityManager:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
    //这个可以放在需要侦听的页面//
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(afNetworkStatusChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
    [afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:{
                NSLog(@"网络不通：%@",@(status) );
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:{
                NSLog(@"网络通过WIFI连接：%@",@(status));
                if (!self.isHaveAdInfo) {
                    [self getInfo_application:application didFinishLaunchingWithOptions:launchOptions];
                }
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN:{
                NSLog(@"网络通过无线连接：%@",@(status) );
                if (!self.isHaveAdInfo) {
                    [self getInfo_application:application didFinishLaunchingWithOptions:launchOptions];
                    
                }
                break;
            }
            default:
                break;
                
        }
        
    }];
    [afNetworkReachabilityManager startMonitoring];  //开启网络监视器；
}
- (void)getInfo_application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"第三方库初始化 ======第三方库初始化   =====第三方库初始化");
    //第三方库初始化
    //配置广告
    [self configAd];
}

//初始化地图
- (void)configMap {
    [AMapServices sharedServices].apiKey = @"5a2d16546f46562760dc6d51b4635aa7";
    [[AMapServices sharedServices] setEnableHTTPS:YES];
}

-(UIInterfaceOrientationMask)application:(UIApplication * )application
 supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}

/** 服务配置接口 */
- (void)loadAPPServerConfig {
    [HNSH_UserNetServer requestAPPServerConfigSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [[NSUserDefaults standardUserDefaults] setObject:responseObject.resultset forKey:KSaveProtocolAddressID];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

/** 获取配置接口 */
- (void)requestAppStoreConfig{
    [HNSH_UserNetServer requestAPPLastVersionSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSDictionary * data = responseObject.resultset;
            NSArray * version = [data objectForKey:@"versions"];
            if ([version isKindOfClass:[NSArray class]]
                && version.count > 0) {
                NSDictionary * newerDic = [version firstObject];
                NSString * code = [newerDic objectForKey:@"code"];
                NSString * ver = [UIApplication sharedExtensionApplication].appVersion;
                if ([self compareWithVersion1:code version2:ver] == 1) {
                    NSString * message = [newerDic objectForKey:@"message"];
                    CGFloat height = [message heightForFont:[UIFont systemFontOfSize:23] width:206];
                    HNSH_UploadAppAlert *alert = [[HNSH_UploadAppAlert alloc]initWithFrame:CGRectMake(0, 0, 266, 221+height)];
                    alert.desString = message;
                    [alert showView];
                }
            }
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//版本号比大小
- (int)compareWithVersion1:(NSString *)version1 version2:(NSString *)version2 {
    // 获取各个版本号对应版本信息
    NSMutableArray *verArr1 = [NSMutableArray arrayWithArray:[version1 componentsSeparatedByString:@"."]];
    NSMutableArray *verArr2 = [NSMutableArray arrayWithArray:[version2 componentsSeparatedByString:@"."]];
    // 补全版本信息为相同位数
    while (verArr1.count < verArr2.count) {
        [verArr1 addObject:@"0"];
    }
    while (verArr2.count < verArr1.count) {
        [verArr2 addObject:@"0"];
    }
    // 遍历每一个版本信息中的位数
    // 记录比较结果值
    int result = 0;
    for (NSUInteger i = 0; i < verArr1.count; i++) {
        NSInteger versionNumber1 = [verArr1[i] integerValue];
        NSInteger versionNumber2 = [verArr2[i] integerValue];
        if (versionNumber1 < versionNumber2) {
            result = -1;
            break;
        } else if (versionNumber2 < versionNumber1) {
            result = 1;
            break;
        }
    }
    return result;
}

#pragma mark cocnfigAd {
- (void)configAd {
    WeakSelf(weakSelf);
//    return;
    weakSelf.isHaveAdInfo = YES;
    //初始化广告
//    [XHAdSDKManager initWithAppId:@"248199192290263105" success:^{
//        weakSelf.isHaveAdInfo = YES;
//        //初始化开屏--(可选)
//        [XHAdSDKManager initSplashWithAppId:@"248499608345378912" success:^{
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [[HNSH_SplashToors share]showADWithController:(ST_BaseViewController *)weakSelf.window.rootViewController];
//            });
//        } failure:^{
//            
//        }];
//    } failure:^{
//        weakSelf.isHaveAdInfo = NO;
//    }];
//    //初始化激励视频--(可选)
//    [XHAdSDKManager initRewardAdWithAppId:@"248200204069634093" success:^{
//        
//    } failure:^{
//        
//    }];
//    //初始化插页--(可选)
//    [XHAdSDKManager initInterAdWithAppId:@"248575688326512648" success:^{
//
//    } failure:^{
//
//    }];
//    //初始化banner--(可选)
//    [XHAdSDKManager initBannerAdWithAppId:@"248199686639321121" success:^{
//
//    } failure:^{
//
//    }];
//    //初始化信息流--(可选)
//    [XHAdSDKManager initFeedAdWithAppId:@"289121257167781981"];
//    //初始化Draw--(可选)
//    [XHAdSDKManager initDrawAdWithAppId:@"289150002507284541"];
    
//    [self requestIDFA];
}

- (void)requestIDFA{
    if (@available(iOS 14, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            
        }];
    }
}


- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    [[HNSH_AlipayToors shareToors] alipayApplication:app openURL:url options:options];
    return YES;
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    [[HNSH_AlipayToors shareToors] alipayApplication:application openURL:url sourceApplication:sourceApplication annotation:annotation];
    return YES;
}

@end
